package login

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/app/entity"
	"sg-backend/app/entity/userQuery"
	"sg-backend/app/service/userService"
	"sg-backend/config"
	businessError "sg-backend/error"
	"sg-backend/global"
	"sg-backend/model/user"
	"sg-backend/utils"
	"time"
)

// PasswordLogin  用户密码登录
func PasswordLogin(c *fiber.Ctx) error {
	var loginDto entity.PasswordLoginDto
	if err := c.BodyParser(&loginDto); err != nil {
		panic(businessError.New(businessError.BAD_REQUEST))
	}

	if loginDto.Password == "" || loginDto.Account == "" {
		panic(businessError.New(businessError.PARAMS_ERROR))
	}

	// 判断用户是否存在
	qo := &userQuery.GetUserByAccountQo{Account: loginDto.Account}
	userObj := userService.GetUserByAccount(qo)
	if userObj == nil {
		panic(businessError.New(businessError.USER_NOT_FOUND))
	}

	// 判断密码是否相等
	passwordStr := utils.SHAEncrypt(loginDto.Password + userObj.PasswordSalt)
	if passwordStr != userObj.Password {
		panic(businessError.New(businessError.USER_LOGIN_ERROR))
	}

	// 判断用户是否被锁定
	if !userObj.IsActive {
		panic(businessError.New(businessError.USER_LOCKED))
	}

	// 限制在线用户数的，再此处验证

	// 验证通过，创建token
	token := utils.CreateToken(userObj.Id)

	// 将token写入数据库
	newToken := user.Token{
		Token:      token,
		UserId:     userObj.Id,
		JoinTime:   time.Now(),
		ExpireTime: time.Now().Add(config.TTL), // 计算token过期时间
	}

	// 写入数据库
	r := global.DB.Save(&newToken)
	if r.Error != nil {
		global.SLog.Error("Token写入数据库出错", r.Error)
	}

	// token创建保存成功
	// 更新登录时间
	currentTime := time.Now()
	userObj.LastLoginTime = &currentTime
	global.DB.Save(&userObj)

	// 初次登录
	isFirstLogin := "no"
	if userObj.IsFirstLogin {
		isFirstLogin = "yes"
	}

	// 返回
	return c.JSON(fiber.Map{
		"success":        true,
		"message":        "验证成功！",
		"access":         token,
		"is_first_login": isFirstLogin,
	})
}
